package com.xywang.dao.user;

import com.mysql.cj.util.StringUtils;
import com.xywang.dao.BaseDao;
import com.xywang.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// where userCode= 用户名  根据该条件，将一行数据取出，存入一个user对象中
public class UserDaoImpl implements UserDao{
    @Override
    // 得到要登录的用户
    public User getLoginUser(Connection connection, String userCode) throws SQLException {
        // 根据用户名，获取登录用户
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;

        if (connection != null) {
            String sql = "select * from smbms_user where userCode=?";
            Object[] params = {userCode};

            rs = BaseDao.execute(connection, pstm, rs, sql, params);
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                }
                BaseDao.closeResource(null,pstm,rs);

        }
        return user;
    }

    // 修改用户密码
    @Override
    public int updatePwd(Connection connection, int id, String password) throws SQLException {
        PreparedStatement pstm = null;
        int i = 0;
        if(connection!=null){
            String sql = "update smbms_user set userPassword = ? where id =?";
            Object[] params = {password, id};
            i = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return i;
    }

    // 根据用户名或者角色查询用户‘总数’
    @Override
    public int getUserCount(Connection connection, String username, int userrole) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        ArrayList<Object> list = new ArrayList<>();
        int count=0;

        // 重点难点在于sql拼接
        if(connection!=null){
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT count(1) as count from smbms_user u,smbms_role r where u.userRole=r.id");

             /*
                如果用户名存在，则在StringBuffer类型的sql中继续拼接上按名字查询的条件
                并且将名字添加到列表中，作为sql的参数
             */
            if(!StringUtils.isNullOrEmpty(username)){
                sql.append(" and u.userName like ?");
                list.add("%"+username+"%");// index:0
            }
            /*
            * 前端把0当作没有选择角色作为条件查询，所以当userrole>0时，
            * 拼接以角色作为条件的查询，在列表添加参数
            * */
            if(userrole>0){
                sql.append(" and u.userRole = ?");
                list.add(userrole);// index:1
            }

            // 把List转换为数组，list现在存放了sql的参数，转换为数组，调用工具类查询
            Object[] params = list.toArray();

            rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
            if(rs.next()){
                count = rs.getInt("count");
            }
            BaseDao.closeResource(null, pstm,rs);
        }
        // 输出最后完整的sql语句，调试错误用
        // System.out.println("dao层-->UserDaoImpl-->getUserCount:  "+sql.toString());
        return count;
    }

    //  通过条件返回用户‘列表’
    @Override
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {

        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<User>();

        if (connection != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
            List<Object> list = new ArrayList<Object>();

            if (!StringUtils.isNullOrEmpty(userName)) {
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");
            }
            if (userRole > 0) {
                sql.append(" and u.userRole = ?");
                list.add(userRole);
            }
            //在mysql数据库中，分页使用 limit startIndex，pageSize ; 总数
            // 当前页=（当前页-1）*页而大小
            // 0,5    1  01234
            // 5,5    2  56789
            // 10,5   3  10~
            // currentPageNo 当前页
            // pageSize 页面大小
            sql.append(" order by creationDate DESC limit ?,?");
            // 当前页 1 ，则为 limit 0,pageSize;
            // 当前页 2 ，则为 limit 5,pageSize;
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo);
            list.add(pageSize);

            Object[] params = list.toArray();
            // 调试用
            // System.out.println("sql ----> " + sql.toString());
            rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
            while (rs.next()) {
                User _user = new User();
                _user.setId(rs.getInt("id"));
                _user.setUserCode(rs.getString("userCode"));
                _user.setUserName(rs.getString("userName"));
                _user.setGender(rs.getInt("gender"));
                _user.setBirthday(rs.getDate("birthday"));
                _user.setPhone(rs.getString("phone"));
                _user.setUserRole(rs.getInt("userRole"));
                _user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(_user);
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return userList;
    }

    // 添加用户
    @Override
    public int addUserDao(Connection connection, User user) throws SQLException {
        PreparedStatement pstm = null;
        int i = 0;
        if(connection!=null){
            String sql = "INSERT into smbms_user(userCode,userName,userPassword," +
            "gender,birthday,phone,address,userRole,createdBy,creationDate) values(?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {user.getUserCode(),user.getUserName(),
                    user.getUserPassword(),user.getGender(),
                    user.getBirthday(),user.getPhone(),
                    user.getAddress(),user.getUserRole(),
                    user.getCreatedBy(),user.getCreationDate()};
            i = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
            System.out.println("Object[] params ="+Arrays.toString(Arrays.stream(params).toArray()));
        }
        return i;
    }

    // 删除用户
    @Override
    public int deleteUser(Connection connection, int id) throws SQLException {
        PreparedStatement pstm = null;
        int i = 0;
        if(connection!=null){
            String sql = "delete from smbms_user where id=?";
            Object[] params = {id};
            i = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return i;
    }

    // 通过id得到用户
    @Override
    public User getUserById(Connection connection, int id) throws SQLException {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if (null != connection) {
            String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
            Object[] params = {id};
            rs = BaseDao.execute(connection, pstm, rs, sql, params);
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return user;
    }
    // 修改用户
    @Override
    public int updateUser(Connection connection, User user) throws SQLException {
        PreparedStatement pstm = null;
        int i = 0;
        if(connection!=null){
            String sql = "update smbms_user set userName=?,gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {user.getUserName(), user.getGender(), user.getBirthday(),
                    user.getPhone(), user.getAddress(), user.getUserRole(), user.getModifyBy(),
                    user.getModifyDate(), user.getId()};
            i = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return i;
    }


}
